package com.mjf.gmall.publisher.contorller;

import com.alibaba.fastjson.JSON;
import com.mjf.gmall.publisher.service.EsService;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
public class PublisherContorller {

    @Autowired
    EsService esService;

    /**
     * http://publisher:8070/realtime-total?date=2021-04-26
     * @param dt date=2021-04-26
     * @return [{"id":"dau","name":"新增日活","value":1200},{"id":"new_mid","name":"新增设备","value":233}]
     */
    @RequestMapping(value = "realtime-total", method = RequestMethod.GET)
    public String realtimeTotal(@RequestParam("date") String dt){

        List<Map<String,Object>> rsList = new ArrayList<>();

        Map<String,Object> dauMap = new HashMap<>();
        dauMap.put("id", "dau");
        dauMap.put("name", "新增日活");
        if(esService.getDauTotal(dt) != null) {
            dauMap.put("value", esService.getDauTotal(dt));
        } else {
            dauMap.put("value", 0);
        }
        rsList.add(dauMap);

        Map<String,Object> newMidMap = new HashMap<>();
        newMidMap.put("id", "new_mid");
        newMidMap.put("name", "新增设备");
        newMidMap.put("value", 233);    // 新增设备需求没做，写死
        rsList.add(newMidMap);

        return JSON.toJSONString(rsList);

    }


    /**
     * http://publisher:8070/realtime-hour?id=dau&date=2021-04-26
     * @param dt date=2021-04-26
     * @return {"yesterday":{"11":383,"12":123,"17":88,"19":200 },"today":{"12":38,"13":1233,"17":123,"19":688 }}
     */
    @RequestMapping(value = "realtime-hour", method = RequestMethod.GET)
    public String realtimeHour(@RequestParam("id") String id, @RequestParam("date") String dt){

        Map<String, Map<String,Long>> rsMap = new HashMap();

        Map dauHourMapTD = esService.getDauHour(dt);
        rsMap.put("today", dauHourMapTD);

        String yd = getYd(dt);
        Map dauHourMapYD = esService.getDauHour(yd);
        rsMap.put("yesterday", dauHourMapYD);

        return JSON.toJSONString(rsMap);

    }


    /**
     * 将 今天字符串日期 转为 昨天字符串日期
     * @param today 今天字符串日期
     * @return 昨天字符串日期
     */
    public String getYd(String today) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date todayDate = sdf.parse(today);
            Date ydDate = DateUtils.addDays(todayDate, -1);
            return sdf.format(ydDate);
        } catch (ParseException e) {
            e.printStackTrace();
            throw new RuntimeException("日期格式不正确");
        }
    }

}
